﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAO;
using Common;
using WebComputers.Class;

namespace WebComputers.AdministratorHA
{
    public partial class frmDanhMucHangHoa : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["DMHHSave"] = Server.UrlEncode(System.DateTime.Now.ToString());
                FillDataComboBox();
                FillData();
            }
            else
            {
                if (grvDanhMucHangHoa.Rows.Count > 0)
                {
                    grvDanhMucHangHoa.HeaderRow.TableSection = TableRowSection.TableHeader;
                }
            }
        }

        private void FillDataComboBox()
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("PageSize", typeof(System.Int32));

                for (int i = 10; i <= 40; i += 10)
                {
                    dt.Rows.Add(i);
                }
                ddlPageSize.DataSource = dt;
                ddlPageSize.DataTextField = "PageSize";
                ddlPageSize.DataValueField = "PageSize";
                ddlPageSize.DataBind();
                hdfPageSize.Value = ddlPageSize.SelectedItem.Value;

                ddlDonViTinh.DataSource = DonViTinhDAO.SelectAll();
                ddlDonViTinh.DataTextField = "sTenDonViTinh";
                ddlDonViTinh.DataValueField = "iDonViTinh_ID";
                ddlDonViTinh.DataBind();

                ddlLoaiHangHoa.DataSource = LoaiHangHoaDAO.SelectAll();
                ddlLoaiHangHoa.DataTextField = "sTenLoai";
                ddlLoaiHangHoa.DataValueField = "iLoaiHangHoa_ID";
                ddlLoaiHangHoa.DataBind();

            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }

        private void FillData()
        {
            try
            {
                //DataTable dt = BindGridView();
                //if (dt.Rows.Count > 0)
                //{
                //    dt.Columns.Add("STT", typeof(System.Int32));
                //    dt.Columns.Add("imgPopOver", typeof(System.String));
                //    int i = (Convert.ToInt32(txtPageIndex.Text) - 1) * Convert.ToInt32(ddlPageSize.SelectedItem.Value) + 1;
                //    for (int j = 0; j < dt.Rows.Count; j++)
                //    {
                //        dt.Rows[j]["STT"] = i;
                //        dt.Rows[j]["imgPopOver"] = DAHelper.ImagePath() + dt.Rows[j]["sHinhDaiDien"].ToString();
                //        i++;
                //    }
                //}
                //grvDanhMucHangHoa.DataSource = dt;
                //grvDanhMucHangHoa.DataBind();
                //if (grvDanhMucHangHoa.Rows.Count > 0)
                //{
                //    grvDanhMucHangHoa.HeaderRow.TableSection = TableRowSection.TableHeader;
                //}
               
                if (DAHelper.CheckNumber(txtPageIndex.Text))
                {
                    int pageIndex = Convert.ToInt32(txtPageIndex.Text);
                    if (pageIndex <= 0)
                    {
                        grvDanhMucHangHoa.DataSource = null;
                        grvDanhMucHangHoa.DataBind();
                        return;
                    }
                    int pageSize = Convert.ToInt32(ddlPageSize.SelectedItem.Value);
                    int totalPages = Convert.ToInt32(txtTotalPages.Text);
                    if (totalPages > 0)
                    {
                        if ((pageIndex - 1) * pageSize >= totalPages * Convert.ToInt32(hdfPageSize.Value))
                        {
                            //pageIndex = 1;
                            pageIndex = (int)Math.Ceiling((double)(totalPages * Convert.ToInt32(hdfPageSize.Value)) / pageSize);
                            txtPageIndex.Text = pageIndex.ToString();
                        }
                    }
                    grvDanhMucHangHoa.DataSource = DanhMucHangHoaDAO.SelectAllLinqForPaging(pageIndex, pageSize, ref totalPages);
                    grvDanhMucHangHoa.DataBind();
                    txtTotalPages.Text = DAHelper.CalculateTotalPages(totalPages, pageSize).ToString();
                    hdfPageSize.Value = pageSize.ToString();
                }
                if (grvDanhMucHangHoa.Rows.Count > 0)
                {
                    grvDanhMucHangHoa.HeaderRow.TableSection = TableRowSection.TableHeader;
                }

            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }

        private DataTable BindGridView()
        {
            try
            {
                DataTable dt = new DataTable();
                if (DAHelper.CheckNumber(txtPageIndex.Text))
                {
                    int pageIndex = Convert.ToInt32(txtPageIndex.Text);
                    if (pageIndex <= 0) return dt;
                    int pageSize = Convert.ToInt32(ddlPageSize.SelectedItem.Value);
                    int totalPages = Convert.ToInt32(txtTotalPages.Text);
                    if (totalPages > 0)
                    {
                        if ((pageIndex - 1) * pageSize >= totalPages * Convert.ToInt32(hdfPageSize.Value))
                        {
                            //pageIndex = 1;
                            pageIndex = (int)Math.Ceiling((double)(totalPages * Convert.ToInt32(hdfPageSize.Value)) / pageSize);
                            txtPageIndex.Text = pageIndex.ToString();
                        }
                    }
                    dt = DanhMucHangHoaDAO.SelectAllForPaging(pageIndex, pageSize, ref totalPages);
                    txtTotalPages.Text = DAHelper.CalculateTotalPages(totalPages, pageSize).ToString();
                    hdfPageSize.Value = pageSize.ToString();
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void grvDanhMucHangHoa_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(grvDanhMucHangHoa.DataKeys[e.RowIndex].Value);
                DanhMucHangHoaDAO.DeleteLinq(id);
                FillData();
            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }

        protected void grvDanhMucHangHoa_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(grvDanhMucHangHoa.DataKeys[e.NewSelectedIndex].Value);
                DanhMucHangHoa dmhh = DanhMucHangHoaDAO.SelectByIdLinq(id);
                cbBanChay.Checked = dmhh.bBanChay;
                cbDacBiet.Checked = dmhh.bDacBiet;
                cbQuanLy.Checked = dmhh.bQuanLy;
                cbTrangChu.Checked = dmhh.bTrangChu;
                txtGiaBan.Text = dmhh.dGiaBan.ToString();
                txtGiaKhuyenMai.Text = dmhh.dGiaKhuyenMai.ToString();
                if (dmhh.dGiaKhuyenMai > 0)
                    cbKhuyenMai.Checked = true;
                else
                    cbKhuyenMai.Checked = false;
               
                hdfID.Value = dmhh.iDanhMucHangHoa_ID.ToString();
                //ddlDonViTinh.SelectedItem.Value = dmhh.iDonViTinh_ID.ToString();
                //ddlLoaiHangHoa.SelectedItem.Value = dmhh.iLoaiHangHoa_ID.ToString();
                ddlDonViTinh.SelectedIndex = ddlDonViTinh.Items.IndexOf(ddlDonViTinh.Items.FindByValue(dmhh.iDonViTinh_ID.ToString()));
                ddlLoaiHangHoa.SelectedIndex = ddlLoaiHangHoa.Items.IndexOf(ddlLoaiHangHoa.Items.FindByValue(dmhh.iLoaiHangHoa_ID.ToString()));
                if (!string.IsNullOrEmpty(dmhh.sHinhDaiDien))
                {
                    hdfHinhDaiDien.Value = "1";
                    imgHinhDaiDien.ImageUrl = DAHelper.ImagePath() + dmhh.sHinhDaiDien;
                }
                else
                {
                    hdfHinhDaiDien.Value = "0";
                    imgHinhDaiDien.ImageUrl = DAHelper.NoImage();
                }
                txtMaHangHoa.Text = dmhh.sMaHangHoa;
                txtMoTa.Text = dmhh.sMoTa;
                txtTenHangHoa.Text = dmhh.sTenHangHoa;                

            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                if (ViewState["DMHHSave"].ToString() == Session["DMHHSave"].ToString())
                {
                    DanhMucHangHoa dmhh = new DanhMucHangHoa();
                    dmhh.bBanChay = cbBanChay.Checked;
                    dmhh.bDacBiet = cbDacBiet.Checked;
                    dmhh.bQuanLy = cbQuanLy.Checked;
                    dmhh.bTrangChu = cbTrangChu.Checked;
                    dmhh.dGiaBan = Convert.ToDecimal(txtGiaBan.Text);
                    if (cbKhuyenMai.Checked && !string.IsNullOrEmpty(txtGiaKhuyenMai.Text))                    
                        dmhh.dGiaKhuyenMai = Convert.ToDecimal(txtGiaKhuyenMai.Text);
                    else
                        dmhh.dGiaKhuyenMai = 0;
                    dmhh.iDonViTinh_ID = Convert.ToInt32(ddlDonViTinh.SelectedItem.Value);
                    dmhh.iLoaiHangHoa_ID = Convert.ToInt32(ddlLoaiHangHoa.SelectedItem.Value);
                    
                    dmhh.sMaHangHoa = txtMaHangHoa.Text;
                    dmhh.sMoTa = Server.HtmlDecode(txtMoTa.Text);
                    dmhh.sTenHangHoa = txtTenHangHoa.Text;
                    if(hdfID.Value == "0")
                    {
                        dmhh.sHinhDaiDien = GetImage();
                        DanhMucHangHoaDAO.InsertLinq(dmhh);
                    }
                    else
                    {
                        
                        dmhh.iDanhMucHangHoa_ID = Convert.ToInt32(hdfID.Value);
                        dmhh.sHinhDaiDien = GetImage(dmhh.iDanhMucHangHoa_ID);
                        DanhMucHangHoaDAO.UpdateLinq(dmhh);
                    }
                    Session["DMHHSave"] = Server.UrlEncode(System.DateTime.Now.ToString());
                    
                }
                ResetField();
                FillData();
            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }
        
        private string GetImage(int id = 0)
        {
            try
            {
                if (fulHinhDaiDien.HasFile)
                {
                    string path = Server.MapPath(DAHelper.ImagePath()) + DAHelper.ImageName(fulHinhDaiDien.FileName);
                    fulHinhDaiDien.SaveAs(path);
                    return DAHelper.ImageName(fulHinhDaiDien.FileName);
                }
                else
                {
                    if (id <= 0)
                        return string.Empty;
                    else
                    {
                        if (hdfHinhDaiDien.Value == "0")
                            return string.Empty;
                        DanhMucHangHoa dmhh = DanhMucHangHoaDAO.SelectByIdLinq(id);                        
                        return dmhh.sHinhDaiDien;
                    }
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        private void ResetField()
        {
            hdfID.Value = "-1";
            hdfHinhDaiDien.Value = "0";
            txtGiaBan.Text = "0";
            txtGiaKhuyenMai.Text = "0";
            txtMaHangHoa.Text = string.Empty;
            txtMoTa.Text = string.Empty;
            txtTenHangHoa.Text = string.Empty;
            imgHinhDaiDien.ImageUrl = string.Empty;
            cbBanChay.Checked = false;
            cbDacBiet.Checked = false;
            cbQuanLy.Checked = false;
            cbTrangChu.Checked = false;
            ddlDonViTinh.SelectedIndex = 0;
            ddlLoaiHangHoa.SelectedIndex = 0;
            cbKhuyenMai.Checked = false;
        }

        protected void ChangePage(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "First":
                    txtPageIndex.Text = "1";
                    break;
                case "Prev":
                    if (DAHelper.CheckNumber(txtPageIndex.Text))
                    {
                        if (Convert.ToInt32(txtPageIndex.Text) > 1)
                            txtPageIndex.Text = (Convert.ToInt32(txtPageIndex.Text) - 1).ToString();
                        else
                            return;
                    }
                    break;

                case "Next":
                    if (DAHelper.CheckNumber(txtPageIndex.Text))
                    {
                        if (Convert.ToInt32(txtPageIndex.Text) < Convert.ToInt32(txtTotalPages.Text))
                            txtPageIndex.Text = (Convert.ToInt32(txtPageIndex.Text) + 1).ToString();
                        else
                            return;
                    }
                    break;

                case "Last":
                    txtPageIndex.Text = txtTotalPages.Text;
                    break;
            }

            FillData();
        }

        protected void txtPageIndex_TextChanged(object sender, EventArgs e)
        {
            try
            {
                FillData();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FillData();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            ViewState["DMHHSave"] = Session["DMHHSave"];
        }

        

    }
}